/**
 * 
 */
package com.cait.dutyfree.security;
/**
 * @author Rasika Kaluwalgoda
 *
 */

import java.io.UnsupportedEncodingException;

import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.KeySpec;

import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;

public class Password {
	    
	private transient Cipher ecipher=null;
	private transient Cipher dcipher=null;
    
	// 8-byte Salt
	byte[] salt = { (byte) 0x19, (byte) 0x6B, (byte) 0xC8, (byte) 0x32,
			(byte) 0xF6, (byte) 0x35, (byte) 0xA3, (byte) 0x03 };

	// Iteration count
	private static final int ITERATIONCOUNT = 19;

	public Password(final String passPhrase) {
		super();
        KeySpec keySpec = null;
        SecretKey key = null;
        AlgorithmParameterSpec paramSpec = null;
		try {
			// Create the key
			keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt,
                    ITERATIONCOUNT);
			key = SecretKeyFactory.getInstance("PBEWithMD5AndDES")
					.generateSecret(keySpec);
			ecipher = Cipher.getInstance(key.getAlgorithm());
			dcipher = Cipher.getInstance(key.getAlgorithm());

			// Prepare the parameter to the ciphers
			paramSpec = new PBEParameterSpec(salt,
                    ITERATIONCOUNT);

			// Create the ciphers
			ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
			dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
		} catch (java.security.InvalidAlgorithmParameterException iapExep) {
            iapExep.printStackTrace();
		} catch (java.security.spec.InvalidKeySpecException iksExep) {            
            iksExep.printStackTrace();
		} catch (javax.crypto.NoSuchPaddingException nspExep) {
            nspExep.printStackTrace();
		} catch (java.security.NoSuchAlgorithmException nsaExep) {
           nsaExep.printStackTrace();
		} catch (java.security.InvalidKeyException ikExep) {
          ikExep.printStackTrace();
		}
	}
	
	public String encrypt(final String str) {
      
        byte[] utf8;
        byte[] enc;
		try {
			// Encode the string into bytes using utf-8
			utf8 = str.getBytes("UTF8");

			// Encrypt
			enc = ecipher.doFinal(utf8);

			// Encode bytes to base64 to get a string
			return new sun.misc.BASE64Encoder().encode(enc);
		} catch (javax.crypto.BadPaddingException bpExep) {
             bpExep.printStackTrace();
		} catch (IllegalBlockSizeException ibExep) {
            ibExep.printStackTrace();
		} catch (UnsupportedEncodingException ueExep) {
            ueExep.printStackTrace();
		} catch (Exception ex) {
            ex.printStackTrace();
		}
		return null;
	}
	
}
